using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour, ISaveManager
{
    public static GameManager instance;

    [HideInInspector] public CheckPoint[] checkPoints;
    [HideInInspector] public string closestCheckPointID;

    private void Awake()
    {
        if (instance == null) instance = this;
        else Destroy(gameObject);

        checkPoints = FindObjectsOfType<CheckPoint>();
    }

    private void Start()
    {
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
            RestartSceene();
    }

    public void RestartSceene()
    {
        SaveManager.instance.SaveGame();
        Scene scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.name);
    }

    public void PauseGame(bool _isPause)
    {
        if(_isPause)
            Time.timeScale = 0;
        else
            Time.timeScale = 1;
    }

    public void LoadData(GameData _data)
    {
        foreach (KeyValuePair<string, bool> pair in _data.checkPoints)
        {
            foreach (CheckPoint checkPoint in checkPoints)
            {
                if (checkPoint.checkPointID == pair.Key && pair.Value == true)
                    checkPoint.ActiveCheckPoint(); 
            }
        }

        closestCheckPointID = _data.closestCheckPointID;

        Invoke("PlacePlayerAtClosestCheckPoint", .1f);

        PlayerManager.instance.EXP = _data.EXP;
    }

    private void PlacePlayerAtClosestCheckPoint()
    {
        foreach (CheckPoint checkPoint in checkPoints)
        {
            if (closestCheckPointID == checkPoint.checkPointID)
                PlayerManager.instance.player.transform.position = checkPoint.transform.position;
        }
    }

    public void SaveData(ref GameData _data)
    {
        if(FindClosestCheckPoint() != null)
            _data.closestCheckPointID = FindClosestCheckPoint().checkPointID;
        _data.checkPoints.Clear();

        foreach(CheckPoint checkPoint in checkPoints) 
        {
            _data.checkPoints.Add(checkPoint.checkPointID, checkPoint.activationStatus);
        }

        _data.EXP = PlayerManager.instance.EXP;
    }

    public CheckPoint FindClosestCheckPoint()
    {
        float closestDistance = Mathf.Infinity;
        CheckPoint closestCheckPoint = null;

        foreach (var checkPoint in checkPoints)
        {
            float distanceToCheckPoint = Vector2.Distance(PlayerManager.instance.player.transform.position, checkPoint.transform.position);

            if(distanceToCheckPoint < closestDistance && checkPoint.activationStatus == true)
            {
                closestDistance = distanceToCheckPoint;
                closestCheckPoint = checkPoint;
            }
        }

        return closestCheckPoint;
    }
}
